package com.ag.contactTree.service;

import java.sql.Connection;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.ag.admin.dao.AdminTbUserDAO;
import com.ag.bean.TbDeptType;
import com.ag.bean.TbUser;
import com.ag.bean.TbUserContact;
import com.ag.bean.TbUserDept;
import com.ag.contactTree.CoordinatTree;
import com.ag.contactTree.EmergencyTree;
import com.ag.contactTree.ExternalTree;
import com.ag.contactTree.MedicineTree;
import com.ag.contactTree.TreeNode;
import com.ag.dao.TbDeptTypeDAO;
import com.ag.zhh.dao.TbUserDeptDAO;
import com.ag.zhh.dao.UserDeptContactDAO;
import com.ag.zhh.dao.UserDeptDAO;
import com.ag.zhh.dao.ZHHEventGradeDAO;
import com.ag.zhh.vo.UserDept;
import com.ag.zhh.vo.UserDeptContact;

/**
 * 本地通信录的树
 * 
 * @author user
 * 
 */
public class LocalTreeService extends HibernateDaoSupport {
	private static final Log log = LogFactory.getLog(LocalTreeService.class);
	private UserDeptDAO userDeptDAO;

	@Resource(name = "adminTbUserDAO")
	private AdminTbUserDAO adminTbUserDAO;
	@Resource(name = "ZHHTbUserDeptDAO")
	private TbUserDeptDAO tbUserDeptDAO;
	private TbDeptTypeDAO deptTypedao;
	private UserDeptContactDAO userDeptContactDAO;
	private Object lock = new Object();

	// private TbUserDAO user;
	/**
	 * 增加树的结点
	 * 
	 * @param dept
	 *            部门
	 * @param deptTypeId
	 *            部门类型
	 */
	public void addTreeNodeByUserDept(UserDept dept, String deptTypeId) {
		try {
			if (dept != null)
				System.out.println("LocalTreeService: 树的id：" + dept.getUdId()
						+ " 树的类型：" + deptTypeId);
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (deptTypeId.equals("0001"))
			CoordinatTree.getInstance(userDeptDAO).addDeptTreeNode(dept);
		else if (deptTypeId.equals("0002"))
			EmergencyTree.getInstance(userDeptDAO).addDeptTreeNode(dept);
		else if (deptTypeId.equals("0003"))
			ExternalTree.getInstance(userDeptDAO).addDeptTreeNode(dept);
		else if (deptTypeId.equals("0000"))
			MedicineTree.getInstance(userDeptDAO).addDeptTreeNode(dept);

	}

	/**
	 * 把树从新从内存中加载
	 */
	public void updateTree() {
		ExternalTree.getInstance(userDeptDAO).reloadExternalDept(userDeptDAO);
		EmergencyTree.getInstance(userDeptDAO).reloadEmergencyDept(userDeptDAO);
		CoordinatTree.getInstance(userDeptDAO).reloadCoordinatDept(userDeptDAO);
		MedicineTree.getInstance(userDeptDAO).reloadMedicineDept(userDeptDAO);
		

	}

	public void cleanTableBySQL(String sql) {
		Session session = null;
		Transaction tr = null;
		// String deleteMiddleTablesql = "delete from tb_dept_and_contact";
		// String deleteContactsql = "delete from tb_contact";
		// String sql = "delete from TB_CONTACT";
		log.info("cleanTableBySQL");
		try {
			/* zhh start(把注释去掉就是原来颢铧的代码，除了//的注释)
			DataSource ds = SessionFactoryUtils
					.getDataSource(getSessionFactory());
			Connection conn = ds.getConnection();

			session = getSession(true);

			tr = session.beginTransaction();
			Statement state = conn.createStatement();
			// 获取connection,执行静态SQL
			// Statement state = session.connection().createStatement();
			// state.executeQuery(deleteMiddleTablesql);
			// log.info("delete from tb_dept_and_contact");
			// state.executeQuery(deleteContactsql);
			// log.info("delete from tb_contact");

			state.executeUpdate(sql);
			log.info(sql);

			tr.commit();
			*/
			//hmk start
			System.out.println("========"+sql);
			session = getHibernateTemplate().getSessionFactory().openSession();
			tr = session.beginTransaction();
			session.createSQLQuery(sql).executeUpdate();
			tr.commit();
			//hmk end
		} catch (Exception e) {
			if (tr != null) {
				log.info("tr rollback");
				tr.rollback();
			}
			e.printStackTrace();
		} finally {

			if (session != null) {
				System.out.println("=====ok33");
				session.close();
			}
		}

	}

	/**
	 * 指定用户的负责部门和所属部门
	 * 
	 * @param uid
	 *            用户id
	 * @param belongs
	 *            所属部门数组
	 */
	public void designatedDept(String uid, String belongs[]) {
		TbUser tbuser = adminTbUserDAO.findById(uid);
		// Set<TbUserDept> userDepts = tbuser.getTbUserDepts();
		//Set<TbUserDept> userDepts = new HashSet<TbUserDept>();
		// tbuser.setTbUserDepts(null);
		//Set<TbUserDept> originDept = tbuser.getTbUserDepts();
		//if (originDept.size() == 0) {
		//	log.info("originDept.size() == 0");
		//}
		log.info("remover igi");
		String deletesql = "delete TB_USERDEPT_USER where U_ID='" + uid + "'";
		cleanTableBySQL(deletesql);
		log.info("remove 所属部门");
		
		log.info("add 所属部门");
		for (String belong : belongs) {
			//TbUserDept dept = tbUserDeptDAO.findTbUserDeptJoinTbUser(belong);
			//tbUserDeptDAO.merge(dept);
			//dept.getTbUsers().add(tbuser);
			//tbUserDeptDAO.attachDirty(dept);
			String intsertsql = "insert into TB_USERDEPT_USER values ('"+uid+"','"+belong+"')";
			UserDept dept =(UserDept)this.getTreeNodeById(belong).getBindData();
			UserDeptContact newUser= new UserDeptContact();
			newUser.setUId(tbuser.getUId());
			newUser.setUTel(tbuser.getUTel());
			newUser.setUPhone(tbuser.getUPhone());
			newUser.setUName(tbuser.getUName());
			newUser.setUMail(tbuser.getUMail());
			newUser.setUFax(tbuser.getUFax());
			if(!dept.getTbUsers().contains(newUser)) dept.getTbUsers().add(newUser);
			cleanTableBySQL(intsertsql);
		}
		// tbuser.setTbUserDepts(userDepts);
		// adminTbUserDAO.attachDirty(tbuser);
		log.info("add 所属部门");
		/*
		 * UserDeptContact user; //Set<UserDept> userChargeDepts = new HashSet<UserDept>(0); //
		 * 负责部门 Set<UserDept> depts = new HashSet<UserDept>(0); // 所属部门 //
		 * 从树中查找出用户的所属部门和负责部门 if (uid == null || uid.equals("")) { return; }
		 * try{ user = userDeptContactDAO.findById(uid);
		 * 
		 * if (belongs != null && belongs.length > 0) { // 用户更改所属部门 for (String
		 * belong : belongs) { if (belong == null || belong.equals("")) {
		 * continue; } TreeNode node = this.getTreeNodeById(belong); UserDept
		 * dept = (UserDept) node.getBindData();
		 * 
		 * depts.add(dept); }
		 * 
		 * userDeptContactDAO.refreshBelongDept(user,depts); //for (UserDept
		 * dept : depts) { // dept.getTbUsers().add(user); //
		 * userDeptDAO.merge(dept); // userDeptDAO.saveOrUpdateDept(dept); //
		 * user.getTbUserDepts().add(dept); // userDeptContactDAO.merge(user); //
		 * userDeptContactDAO.saveOrUpdateContact(user);
		 * //userDeptDAO.addBelongDept(user, dept);
		 * //注意：多对多的经典问题，session中存在有相同id，对象却不同，报错 //different object with the
		 * same identifier value was already associated with the session //}
		 * //userDeptContactDAO.addBelongDept(user, depts);
		 *  } }catch(Exception e){ e.printStackTrace(); }
		 */
	}

	/**
	 * 判断用户部门是否存在负责人
	 * 
	 * @param nodeId
	 *            用户部门ID
	 * @return
	 */
	public boolean checkChargePeopleExist(String nodeId) {
		boolean result = false;
		if (nodeId == null || nodeId.equals("")) {
			return result;
		}
		TreeNode node = getTreeNodeById(nodeId);
		UserDept dept = (UserDept) node.getBindData();
		if (dept.getTbUser() == null) {
			return false;
		}
		return true;
	}

	/**
	 * 查找部门的结点
	 * 
	 * @param nodeId
	 *            部门id
	 * @return
	 * @throws Exception
	 */
	public TreeNode getTreeNodeById(String nodeId) {
		TreeNode node = null;
		try {
			System.out.println("**********\t\t\tTreeService: " + nodeId
					+ "\t\t\t*********************");

			node = getCoordinatTreeNodeById(nodeId);
			if (node == null)
				node = this.getEmergencyTreeNodeById(nodeId);
			if (node == null)
				node = this.getExternalTreeNodeById(nodeId);
			if (node == null)
				node = this.getExternalTreeNodeById(nodeId);
			if (node == null)
				node = this.getMedicineTreeNodeById(nodeId);
		} catch (Exception e) {
			e.printStackTrace();

		}
		return node;
	}

	/**
	 * 查询部门类型
	 * 
	 * @return 查询部门类型
	 */
	public List<TbDeptType> findDeptType() {
		// List<TbDeptType> list = new ArrayList<TbDeptType>();
		// list.add(((UserDept) MedicineTree.getInstance(userDeptDAO)
		// .getRootNode().getBindData()).getTbDeptType());
		// list.add(((UserDept) CoordinatTree.getInstance(userDeptDAO)
		// .getRootNode().getBindData()).getTbDeptType());
		// list.add(((UserDept) EmergencyTree.getInstance(userDeptDAO)
		// .getRootNode().getBindData()).getTbDeptType());
		// list.add(((UserDept) ExternalTree.getInstance(userDeptDAO)
		// .getRootNode().getBindData()).getTbDeptType());
		//		
		// return list;
		return deptTypedao.findAll();
	}

	/**
	 * 输入部门类型id查询部门
	 * 
	 * @param deptTypeId
	 * @return
	 */
	public List<TbUserDept> findBydeptType(String deptTypeId) {
		List<TbUserDept> list = new ArrayList<TbUserDept>();
		try {
			if (deptTypeId == null || deptTypeId.equals("")) {
				System.out.println(" 树的类型：" + deptTypeId);
				return list;
			}
		list = tbUserDeptDAO.findTbUserDeptByDtId(deptTypeId);
//			Set<UserDept> sets = new HashSet<UserDept>();
//			if("0000".equals(deptTypeId))
//			{
//				sets = ((UserDept)this.getMedicineTreeRoot().getBindData()).getTbUserDepts();
//			}
//			else if("0001".equals(deptTypeId))
//			{
//				
//				sets =((UserDept)this.getCoordinatTreeRoot().getBindData()).getTbUserDepts();
//			}
//			else if("0002".equals(deptTypeId))
//			{
//				sets =((UserDept)this.getEmergencyTreeRoot().getBindData()).getTbUserDepts();
//			}
//			else if("0003".equals(deptTypeId))
//			{
//				sets =((UserDept)this.getExternalTreeRoot().getBindData()).getTbUserDepts();
//			}
//
//			for(UserDept dept:sets)
//			{
//				TbUserDept userdept = new TbUserDept();
//				userdept.setUdId(dept.getUdId());
//				userdept.setTbDeptType(dept.getTbDeptType());
//				userdept.setUdName(dept.getUdName());
//				
//			//	list.add(dept);
//			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return list;
		// return userDeptDAO.findByDeptTypeId(deptTypeId);
	}

	/**
	 * 排好序的
	 * @param deptTypeId
	 * @return
	 */

	/**
	 * 
	 * @param nodeType
	 *            更加部门类型id查部门列表
	 * @return map<部门id,部门名>
	 * @throws Exception
	 */
	public Map<String, String> getDepts(String nodeType) {
		Map<String, String> deptmap = new HashMap<String, String>();
		List<TbUserDept> list = tbUserDeptDAO.findTbUserDeptByDtId(nodeType);
		// List<UserDept> list = findBydeptType(nodeType);
		if (list != null && list.size() > 0) {
			for (TbUserDept dept : list) {
				deptmap.put(dept.getUdId(), dept.getUdName());

			}
		}
		return deptmap;

	}

	public CoordinatTree getCoordinatTree() {
		return CoordinatTree.getInstance(userDeptDAO);
	}

	/**
	 * 获取协调部门的树头
	 * 
	 * @return
	 */
	public TreeNode getCoordinatTreeRoot() {
		return CoordinatTree.getInstance(userDeptDAO).getRootNode();
	}

	public ExternalTree getExternalTree() {
		return ExternalTree.getInstance(userDeptDAO);
	}

	/**
	 * 获取外部单位的树头
	 * 
	 * @return
	 */
	public TreeNode getExternalTreeRoot() {
		return ExternalTree.getInstance(userDeptDAO).getRootNode();
	}

	/**
	 * 获取应急部门的树头
	 * 
	 * @return
	 */
	public EmergencyTree getEmergencyTree() {
		return EmergencyTree.getInstance(userDeptDAO);
	}

	public TreeNode getEmergencyTreeRoot() {
		return EmergencyTree.getInstance(userDeptDAO).getRootNode();
	}

	/**
	 * 获取药监内部树
	 * 
	 * @return
	 */
	public MedicineTree getMedicineTree() {
		return MedicineTree.getInstance(userDeptDAO);
	}

	public TreeNode getMedicineTreeRoot() {
		return MedicineTree.getInstance(userDeptDAO).getRootNode();
	}

	public List<TreeNode> getChildrenByFDId(String nodeId) {
		TreeNode node = getTreeNodeById(nodeId);
		List<TreeNode> list = null;
		if (node != null) {
			list = node.getChildren();
		}
		return list;
	}

	public TreeNode getCoordinatTreeNodeById(String nodeId) {
		return CoordinatTree.getInstance(userDeptDAO).getTreeNode(nodeId);
	}

	public TreeNode getEmergencyTreeNodeById(String nodeId) {
		return EmergencyTree.getInstance(userDeptDAO).getTreeNode(nodeId);
	}

	public TreeNode getExternalTreeNodeById(String nodeId) {
		return ExternalTree.getInstance(userDeptDAO).getTreeNode(nodeId);
	}

	public TreeNode getMedicineTreeNodeById(String nodeId) {
		return MedicineTree.getInstance(userDeptDAO).getTreeNode(nodeId);
	}

	public UserDeptDAO getUserDeptDAO() {
		return userDeptDAO;
	}

	public void setUserDeptDAO(UserDeptDAO userDeptDAO) {
		this.userDeptDAO = userDeptDAO;
	}

	public TbDeptTypeDAO getDeptTypedao() {
		return deptTypedao;
	}

	public void setDeptTypedao(TbDeptTypeDAO deptTypedao) {
		this.deptTypedao = deptTypedao;
	}

	public UserDeptContactDAO getUserDeptContactDAO() {
		return userDeptContactDAO;
	}

	public void setUserDeptContactDAO(UserDeptContactDAO userDeptContactDAO) {
		this.userDeptContactDAO = userDeptContactDAO;
	}

}
